package com.boho.system.service;

/**
 * @File name:  PermissionService.java 
 * @Create on:  2010-05-10 19:30:171
 * @Author   :  陈伟
 *
 * @ChangeList
 * ---------------------------------------------------
 * Date         Editor              ChangeReasons
 *
 */


import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.boho.framework.context.ActionContext;
import cn.boho.framework.core.FrameworkConstant;
import cn.boho.framework.exception.UserOperationException;
import cn.boho.framework.log.Logger;
import cn.boho.framework.po.DynaBeanMap;
import cn.boho.framework.po.POUtils;
import cn.boho.framework.service.MessageService;

import com.boho.common.Constant;
import com.boho.common.SystemUtils;
import com.boho.system.dao.TSysFunctionDao;
import com.boho.system.dao.TSysRoleDao;
import com.boho.system.dao.TSysUserDao;
import com.boho.system.po.TRoleFunctionPO;
import com.boho.system.po.TUserFunctionPO;
import com.boho.system.po.TUserRolePO;




/**
 * 权限管理业务类
 * @author 陈伟
 * @date 2010-05-10
 */
public class PermissionService {
	
	@SuppressWarnings("unused")
	private static Logger logger = new Logger(org.apache.log4j.Logger.getLogger(PermissionService.class));
	
	/**
	 * 添加用户角色关系配置
	 * @param atx
	 * @param userid
	 * @param roleids
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void addUserRole(ActionContext atx, Integer userid, Integer[] roleids) throws Exception{
		if(roleids != null){
			Connection con = atx.getConection();
			SystemUtils.getSessionUser(atx);
			List poList = new ArrayList();
			for(Integer roleid : roleids){
				TUserRolePO tUserRolePO = new TUserRolePO();
				tUserRolePO.setUserId(userid);
				tUserRolePO.setRoleId(roleid);
				poList.add(tUserRolePO);
			}
			POUtils.insertPoList(con, poList, false, false);
		}
	}
	
	/**
	 * 修改用户角色关系配置
	 * @param atx
	 * @param userid
	 * @param roleids
	 * @throws Exception
	 */
	public static void updateUserRole(ActionContext atx, Integer userid, Integer[] roleids) throws Exception{
		//删除旧用户角色配置
		deleteUserRole(atx, userid);
		//添加新用户角色配置
		addUserRole(atx, userid, roleids);
	}
	
	/**
	 * 添加角色功能配置
	 * @param atx
	 * @param roleid
	 * @param funids
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void addRoleFunction(ActionContext atx, Integer roleid, String[] funids) throws Exception{
		if(funids != null){
			SystemUtils.getSessionUser(atx);
			Connection con = atx.getConection();
			List poList = new ArrayList();
			for(String funid : funids){
				TRoleFunctionPO tRoleFunctionPO = new TRoleFunctionPO();
				tRoleFunctionPO.setRoleId(roleid);
				tRoleFunctionPO.setFunctionId(funid);
				poList.add(tRoleFunctionPO);
			}
			POUtils.insertPoList(con, poList, false, false);
		}
	}
	
	/**
	 * 修改角色功能配置
	 * @param atx
	 * @param roleid
	 * @param funids
	 * @throws Exception
	 */
	public static void updateRoleFunction(ActionContext atx, Integer roleid, String[] funids) throws Exception{
		//删除旧的角色功能配置信息
		deleteRoleFunction(atx, roleid);
		//添加新的角色功能配置信息
		addRoleFunction(atx, roleid, funids);
	}
	
	/**
	 * 添加用户功能配置
	 * @param atx
	 * @param userid
	 * @param funids
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void addUserFunction(ActionContext atx, Integer userid, String[] funids) throws Exception{
		if(funids != null){
			Connection con = atx.getConection();
			SystemUtils.getSessionUser(atx);
			List poList = new ArrayList();
			for(String funid : funids){
				TUserFunctionPO tUserFunctionPO = new TUserFunctionPO();
				tUserFunctionPO.setUserId(userid);
				tUserFunctionPO.setFunctionId(funid);
				poList.add(tUserFunctionPO);
			}
			POUtils.insertPoList(con, poList, false, false);
		}
	}
	
	/**
	 * 修改用户功能配置
	 * @param atx
	 * @param userid
	 * @param funid
	 * @throws Exception
	 */
	public static void updateUserFunction(ActionContext atx, Integer userid, String[] funids) throws Exception{
		//删除旧的用户功能配置信息
		deleteUserFunction(atx, userid);
		//添加新的用户功能配置信息
		addUserFunction(atx, userid, funids);
	}
	
	/**
	 * 删除用户角色配置
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	public static void deleteUserRole(ActionContext atx, Integer userid) throws Exception{
		TUserRolePO tUserRolePO = new TUserRolePO();
		SystemUtils.getSessionUser(atx);
		tUserRolePO.setUserId(userid);
		POUtils.delete(atx.getConection(), tUserRolePO);
	}
	
	/**
	 * 批量删除用户角色配置
	 * @param atx
	 * @param userids
	 * @throws Exception
	 */
	public static void batchDeleteUserRole(ActionContext atx, Integer[] userids) throws Exception{
		if(userids != null){
			SystemUtils.getSessionUser(atx);
			Connection con = atx.getConection();
			for(Integer userid : userids){
				TUserRolePO tUserRolePO = new TUserRolePO();
				tUserRolePO.setUserId(userid);
				POUtils.delete(con, tUserRolePO);
			}
		}
	}
	
	/**
	 * 删除角色功能配置
	 * @param atx
	 * @param roleid
	 * @throws Exception
	 */
	public static void deleteRoleFunction(ActionContext atx, Integer roleid) throws Exception{
		SystemUtils.getSessionUser(atx);
		TRoleFunctionPO tRoleFunctionPO = new TRoleFunctionPO();
		tRoleFunctionPO.setRoleId(roleid);
		POUtils.delete(atx.getConection(), tRoleFunctionPO);
	}
	
	/**
	 * 批量删除角色功能配置
	 * @param atx
	 * @param roleids
	 * @throws Exception
	 */
	public static void batchDeleteRoleFunction(ActionContext atx, Integer[] roleids) throws Exception{
		if(roleids != null){
			SystemUtils.getSessionUser(atx);
			Connection con = atx.getConection();
			for(Integer roleid : roleids){
				TRoleFunctionPO tRoleFunPO = new TRoleFunctionPO();
				tRoleFunPO.setRoleId(roleid);
				POUtils.delete(con, tRoleFunPO);
			}
		}
	}
	
	/**
	 * 删除用户功能配置
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	public static void deleteUserFunction(ActionContext atx, Integer userid) throws Exception{
		TUserFunctionPO tUserFunctionPO = new TUserFunctionPO();
		SystemUtils.getSessionUser(atx);
		tUserFunctionPO.setUserId(userid);
		POUtils.delete(atx.getConection(),tUserFunctionPO);
	}
	
	/**
	 * 批量删除用户信息
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	public static void batchDeleteUserFunction(ActionContext atx, Integer[] userids) throws Exception{
		if(userids != null){
			Connection con = atx.getConection();
			SystemUtils.getSessionUser(atx);
			for(Integer userid : userids){
				TUserFunctionPO tUserFunPO = new TUserFunctionPO();
				tUserFunPO.setUserId(userid);
				POUtils.delete(con,tUserFunPO);
			}
		}
	}
	
	/**
	 * 根据用户ID查询用户拥有的角色
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static DynaBeanMap getUserRoleByPKUser(ActionContext atx, Integer userid) throws Exception{
		return TSysUserDao.getTSysUserRoleByPk(atx.getConection(), userid);
	}
	
	/**
	 * 根据用户ID查询用户拥有的角色
	 * @param atx
	 * @param userid
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserRoleByPKUser(ActionContext atx, Integer userid) throws Exception{
		return TSysUserDao.queryUserRoleByPKUser(atx.getConection(), userid);
	}
	
	/**
	 * 根据角色ID查询角色拥有的权限
	 * @param atx
	 * @param roleid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryRoleFunctionListByPKRole(ActionContext atx, Integer roleid) throws Exception{
		return TSysRoleDao.queryTSysRoleFunctionByPKRole(atx.getConection(), roleid);
	}
	
	/**
	 * 查询用户角色树
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserRoleTree(ActionContext atx, Integer userid) throws Exception{
		Connection con = atx.getConection();
		List roleList = TSysRoleDao.queryTSysRole(con);
		List userRoleList = queryUserRoleByPKUser(atx, userid);
		int size = roleList.size();
		int userRoleSize = userRoleList.size();
		if(roleList != null){
			for(int i = 0; i < size; i++){
				DynaBeanMap dbmFun = (DynaBeanMap)roleList.get(i);
				Integer roleID = (Integer)dbmFun.get("ROLE_ID");
				boolean isUserRole = false;
				if(userRoleList != null){
					for(int j = 0; j < userRoleSize; j++){
						DynaBeanMap dbmRoleByUser = (DynaBeanMap)userRoleList.get(j);
						if(dbmRoleByUser.containsValue(roleID)){
							isUserRole = true;
							break;
						}
					}
					dbmFun.put("IS_USER_ROLE", isUserRole);
				}
			}
		}
		return roleList;
	}
	
	/**
	 * 查询角色拥有的功能树
	 * @param atx
	 * @param roleid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryRoleFunctionTreeByPKRole(ActionContext atx, Integer roleid) throws Exception{
		List funList = queryFunctionList(atx);
		List funListByRole = queryRoleFunctionListByPKRole(atx,roleid);
		int size = funList.size();
		int sizeByRole = funListByRole.size();
		if(funList != null){
			for(int i = 0; i < size; i++){
				DynaBeanMap dbmFun = (DynaBeanMap)funList.get(i);
				String pkFunction = (String)dbmFun.get("FUNCTION_ID");
				boolean isRoleFun = false;
				if(funListByRole != null){
					for(int j = 0; j < sizeByRole; j++){
						DynaBeanMap dbmFunByRole = (DynaBeanMap)funListByRole.get(j);
						if(dbmFunByRole.containsValue(pkFunction)){
							isRoleFun = true;
							break;
						}
					}
					dbmFun.put("IS_ROLE_FUNCTION", isRoleFun);
				}
			}
		}
		return funList;
	}
	
	/**
	 * 根据用户ID查询用户功能树
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFunctionTreeByPKUser(ActionContext atx, Integer userid) throws Exception{
		List funList = queryFunctionList(atx);
		List listUserAll = queryUserFunctionByPKUserALL(atx, userid);
		if(funList != null){
			int size = funList.size();
			int sizeNormal = listUserAll.size();
			for(int i = 0; i < size; i++){
				DynaBeanMap dbmFun = (DynaBeanMap)funList.get(i);
				String pkFunction = (String)dbmFun.get("FUNCTION_ID");
				boolean isUserFun = false;
				if(listUserAll != null){
					for(int j = 0; j < sizeNormal; j++){
						DynaBeanMap dbmFunctionByUser = (DynaBeanMap)listUserAll.get(j);
						if(dbmFunctionByUser.containsValue(pkFunction)){
							isUserFun = true;
							break;
						}
					}
				}
				dbmFun.put("IS_USER_FUNCTION", isUserFun);
			}
		}
		return funList;
	}
	
	/**
	 * 根据用户ID查询用户所有功能
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryALLUserFunctionByPKUser(ActionContext atx, Integer userid) throws Exception{
		List normalList = queryUserFuncByPKUserNormal(atx, userid);
		List appendList = queryUserFuncByPKUserAppend(atx, userid);
		normalList.addAll(appendList);
		return normalList;
	}
	
	/**
	 * 过滤重复的用户功能
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFunctionByPKUserALL(ActionContext atx, Integer userid) throws Exception{
		List list = queryALLUserFunctionByPKUser(atx, userid);
		List resultList = new ArrayList(new HashSet(list));
		return resultList;
	}
	
	/**
	 * 根据用户角色查询用户所拥有的功能
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFuncByPKUser(ActionContext atx, Integer userid) throws Exception{
		List roleListByPKUser = queryUserRoleByPKUser(atx, userid);
		List list = new LinkedList();
		if(roleListByPKUser != null){
			int size = roleListByPKUser.size();
			DynaBeanMap dbmRole = null;
			for(int i = 0; i < size; i++){
				dbmRole = (DynaBeanMap)roleListByPKUser.get(i);
				List tmpLstFunction = queryRoleFunctionListByPKRole(atx, (Integer)dbmRole.get("ROLE_ID"));
				list.addAll(tmpLstFunction);
			}
		}
		return list;
	}
	
	/**
	 * 过滤重复的用户功能
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFuncByPKUserNormal(ActionContext atx, Integer userid) throws Exception{
		List list = queryUserFuncByPKUser(atx,userid);
		List userFuncList = new ArrayList(new HashSet(list));
		return userFuncList;
	}
	
	/**
	 * 查询用户附加权限
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFuncByPKUserAppend(ActionContext atx, Integer userid) throws Exception{
		return TSysUserDao.queryUserFuncByPKUserAppend(atx.getConection(), userid);
	}
	
	/**
	 * 根据用户ID查询用户拥有的功能
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryUserFunctionByPKUser(ActionContext atx, Integer userid) throws Exception{
		return TSysUserDao.queryUserFuncByPKUser(atx.getConection(), userid);
	}
	
	/**
	 * 查询用户菜单
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryMenuByPKUser(ActionContext atx) throws Exception{
		Integer userID = (Integer)atx.getSessionValue(Constant.SESSION_USER_NO);
		if(userID == null || "".equals(userID.toString())){
			return null;
		}
		List list = (List)atx.getSessionValue(Constant.SESSION_MENU);
		if(list != null){
			return list;
		}
		list = queryALLUserFunctionByPKUser(atx, userID);
		if(list != null){
			for(int i = list.size()-1; i >= 0; i--){
				DynaBeanMap dbm = (DynaBeanMap)list.get(i);
				String level = dbm.get("FUNCTION_LEVEL").toString();
				if(!Constant.FUNCTION_TYPE_NODE.equals(level)){
					list.remove(i);
				}
			}
		}
		filterMenu(list);
		atx.setSessionValue(Constant.SESSION_MENU, list);
		return list;
	}
	/**
	 * 过滤重复菜单
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private static List filterMenu(List<DynaBeanMap> list) throws Exception{
		if(!list.isEmpty()){
			Map<String,DynaBeanMap> map = new TreeMap<String,DynaBeanMap>();
			String id = null;
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				DynaBeanMap listdbm = (DynaBeanMap) iterator.next();
				id = (String)listdbm.get("FUNCTION_ID");
				map.put(id, listdbm);
			}
			list.clear();
			list.addAll(map.values());
		}
		return list;
	}
	/**
	 * 根据用户ID查询拥有的操作权限
	 * @param atx
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> queryActionByPKUser(ActionContext atx, Integer userid) throws Exception{
		List listAll = queryUserFunctionByPKUserALL(atx, userid);
		Map<String,String> actionMap = null;
		if(listAll != null){
			actionMap = new HashMap<String, String>();
			DynaBeanMap actionDbm = Constant.actionDbm;
			int size = listAll.size();
			for(int i = 0; i < size; i++){
				DynaBeanMap dbm = (DynaBeanMap)listAll.get(i);
				String pkFun = (String)dbm.get("FUNCTION_ID");
				List list = (List)actionDbm.get(pkFun);
				if(list!=null){
					int listSize = list.size();
					for(int j = 0; j < listSize; j++){
						DynaBeanMap dbmAction = (DynaBeanMap)list.get(j);
						String pkAction = (String)dbmAction.get("ACTION_ID");
						String actionName = (String)dbmAction.get("ACTION_NAME");
						actionMap.put(pkAction, actionName);
					}
				}
			}
		}
		return actionMap;
	}
	
	/**
	 * 判断是否显示按钮
	 * @param atx
	 * @param permissionName
	 * @param action
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static DynaBeanMap hasPermission(ActionContext atx, String[] permissionName, String[] action) throws Exception{
		if(FrameworkConstant.CHANNEL_JSON_IS_NEED_ACL == false){
			DynaBeanMap dbm = new DynaBeanMap();
			for(int i = 0; i < permissionName.length; i++){
				dbm.put(permissionName[i], true);
			}
			return dbm;
		}
		if(permissionName.length != action.length){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("FSTI_SYS_PERMISSION_1002", MessageService.getMessage("FSTI_SYS_PERMISSION_1002"), uoe);
		}
		List permissionList = permissionList(atx);
		DynaBeanMap dbm = new DynaBeanMap();
		for(int i = 0; i < permissionName.length; i++){
			if(permissionList.contains(action[i])){
				dbm.put(permissionName[i], true);
			}
			else{
				dbm.put(permissionName[i], false);
			}
		}
		return dbm;
	}
	
	/**
	 * 查询登录用户的权限用户前台验证是否显示事件按钮
	 * @param atx
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List permissionList(ActionContext atx) throws Exception{
		Map permissionMap = queryPermissionByLoginUser(atx);
		Collection collection = permissionMap.values();
		List list = new ArrayList();
		list.addAll(collection);
		return list;
	}
	
	/**
	 * 查询登录用户权限
	 * @param atx
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> queryPermissionByLoginUser(ActionContext atx) throws Exception{
		Map<String,String> actions = (Map<String,String>)atx.getSessionValue(Constant.SESSION_ACTION);
		if(actions == null){
			Integer userID = (Integer)atx.getSessionValue(Constant.SESSION_USER_NO);
			//已登陆
			if(userID != null){
				actions = queryActionByPKUser(atx,userID);
				//保存SESSION
				atx.setSessionValue(Constant.SESSION_ACTION, actions);
			}
		}
		return actions;
	}
	
	/**
	 * 查询系统所有功能
	 * @param atx
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List queryFunctionList(ActionContext atx) throws Exception{
		return TSysFunctionDao.queryTSysFunction(atx.getConection());
	}
}
